package com.cuz.hot100;

import java.util.Stack;

public class Q20validParentheses {
    public static void main(String[] args) {
        System.out.println(new Q20validParentheses().isValid("()"));
    }
    public boolean isValid(String s) {
        if (s == null || s.length() == 0) {
            return true;
        }
        char[] chars = s.toCharArray();
        if (chars.length % 2 != 0) {
            return false;
        }
        Stack<Character> stack = new Stack<>();
        for (char loop : chars) {
            if (loop == '(' || loop == '[' || loop == '{') {
                stack.push(loop);
            }else {
                if (loop==')'){
                    if (stackPeek(stack)!='('){
                        return false;
                    }else {
                        stack.pop();
                    }
                }
                if (loop==']'){
                    if (stackPeek(stack)!='['){
                        return false;
                    }else {
                        stack.pop();
                    }
                }
                if (loop=='}'){
                    if (stackPeek(stack)!='{'){
                        return false;
                    }else {
                        stack.pop();
                    }
                }
            }
        }
        return stack.isEmpty();
    }
    private char stackPeek(Stack<Character> stack ){
        if (stack.isEmpty()){
            return '#';
        }else {
            return stack.peek();
        }
    }
}
